import { Injectable } from '@nestjs/common'
import { createClient, RedisClient } from 'redis'
import { Observable } from 'rxjs'

@Injectable()
export class RedisService {
  client: RedisClient
  constructor() {
    this.client = createClient()
  }

  /**
   * EX seconds -- Set the specified expire time, in seconds.
   * PX milliseconds -- Set the specified expire time, in milliseconds.
   * NX -- Only set the key if it does not already exist.
   * XX -- Only set the key if it already exist.
   * @param key
   * @param value
   */
  set(
    key: string,
    value: string,
    mode: 'EX' | 'PX' | 'NX' | 'XXs',
    duration: number
  ): Observable<void> {
    return Observable.create(obser => {
      this.client.set(key, value, mode, duration, (err: Error | null, reply: string) => {
        if (err) {
          obser.error(err)
        } else {
          obser.next()
          obser.complete()
        }
      })
    })
  }

  /**
   * 获取
   * @param key
   */
  get(key: string): Observable<string> {
    return Observable.create(obser => {
      this.client.get(key, (err: Error | null, reply: string) => {
        if (err) {
          obser.next(null)
          obser.complete()
        }
        if (reply) {
          obser.next(reply)
          obser.complete()
        } else {
          obser.next(null)
          obser.complete()
        }
      })
    })
  }
}
